package customer

import (
	"counter-help/admin/server/global"
	"counter-help/admin/server/model/common/response"
	"counter-help/admin/server/model/customer"
	customerReq "counter-help/admin/server/model/customer/request"
	"counter-help/admin/server/utils"
	"fmt"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"io"
	"os"
	"path/filepath"
)

const OrderAttachPath = "./order/attachFiles"

type CusOrderApi struct{}

// CreateCusOrder 创建cusOrder表
// @Tags CusOrder
// @Summary 创建cusOrder表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body customer.CusOrder true "创建cusOrder表"
// @Success 200 {object} response.Response{msg=string} "创建成功"
// @Router /cusOrder/createCusOrder [post]
func (cusOrderApi *CusOrderApi) CreateCusOrder(c *gin.Context) {

	// 获取上传的文件
	file, header, err := c.Request.FormFile("file")
	if err != nil {
		global.GVA_LOG.Error("获取文件失败" + err.Error())
		response.FailWithMessage("接收文件失败！", c)
		return
	}

	defer file.Close()

	// 读取请求中的 JSON 数据
	var cusOrder customerReq.CreateCusOrder

	// 注意：ShouldBindJSON 会消耗掉 request body，如果你在此之前已经调用 FormFile 读取了文件，就会报 EOF 错误。
	// 由于 Gin 在处理表单时会将文件和其他表单字段混合处理，你可以使用 `c.ShouldBind` 而不是 `ShouldBindJSON` 来处理整个表单。
	err = c.ShouldBind(&cusOrder)
	if err != nil {
		response.FailWithMessage("cusOrder参数解析失败", c)
		return
	}

	// 判断存储地址是否有问题
	if err := os.MkdirAll(OrderAttachPath, os.ModePerm); err != nil {
		response.FailWithMessage("创建存储文件夹失败", c)
		return
	}

	// 保存文件到服务器
	filePath := filepath.Join(OrderAttachPath, header.Filename)
	out, err := os.Create(filePath)
	if err != nil {
		response.FailWithMessage("保存上传文件失败", c)
		return
	}
	defer out.Close()

	// 写入文件
	_, err = io.Copy(out, file)
	if err != nil {
		response.FailWithMessage("写入文件失败", c)
		return
	}

	// 创建订单
	order := customer.CusOrder{
		Title:           cusOrder.Title,
		BussType:        cusOrder.BussType,
		BussSubType:     cusOrder.BussSubType,
		ResearchPurpose: cusOrder.ResearchPurpose,
		ResearchDesign:  cusOrder.ResearchDesign,
		Background:      cusOrder.Background,
		AnRequire:       cusOrder.AnRequire,
		Status:          1,
		DataType:        cusOrder.DataType,
		ItemType:        cusOrder.ItemType,
		Attach:          filePath,
		BudgetMin:       cusOrder.BudgetMin,
		BudgetMax:       cusOrder.BudgetMax,
		InvolvedField:   cusOrder.InvolvedField,
		DataIsFinish:    cusOrder.DataIsFinish,
		Other:           cusOrder.Other,
		UrgencyDegree:   cusOrder.UrgencyDegree,
		OrderUserId:     int(utils.GetUserID(c)),
	}

	// 调用服务创建订单
	err = cusOrderService.CreateCusOrder(&order)
	if err != nil {
		response.FailWithMessage("创建失败:"+err.Error(), c)
		return
	}

	fmt.Println("Order created successfully") // 打印成功日志
	response.OkWithMessage("创建成功", c)
}

// DeleteCusOrder 删除cusOrder表
// @Tags CusOrder
// @Summary 删除cusOrder表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body customer.CusOrder true "删除cusOrder表"
// @Success 200 {object} response.Response{msg=string} "删除成功"
// @Router /cusOrder/deleteCusOrder [delete]
func (cusOrderApi *CusOrderApi) DeleteCusOrder(c *gin.Context) {
	ID := c.Param("ID") // 改为使用路径参数
	err := cusOrderService.DeleteCusOrder(ID)
	if err != nil {
		global.GVA_LOG.Error("删除失败!", zap.Error(err))
		response.FailWithMessage("删除失败:"+err.Error(), c)
		return
	}
	response.OkWithMessage("删除成功", c)
}

// DeleteCusOrderByIds 批量删除cusOrder表
// @Tags CusOrder
// @Summary 批量删除cusOrder表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Success 200 {object} response.Response{msg=string} "批量删除成功"
// @Router /cusOrder/deleteCusOrderByIds [delete]
func (cusOrderApi *CusOrderApi) DeleteCusOrderByIds(c *gin.Context) {
	IDs := c.QueryArray("IDs[]")
	err := cusOrderService.DeleteCusOrderByIds(IDs)
	if err != nil {
		global.GVA_LOG.Error("批量删除失败!", zap.Error(err))
		response.FailWithMessage("批量删除失败:"+err.Error(), c)
		return
	}
	response.OkWithMessage("批量删除成功", c)
}

// UpdateCusOrder 更新cusOrder表
// @Tags CusOrder
// @Summary 更新cusOrder表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body customer.CusOrder true "更新cusOrder表"
// @Success 200 {object} response.Response{msg=string} "更新成功"
// @Router /cusOrder/updateCusOrder [put]
func (cusOrderApi *CusOrderApi) UpdateCusOrder(c *gin.Context) {
	var cusOrder customer.CusOrder
	err := c.ShouldBindJSON(&cusOrder)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = cusOrderService.UpdateCusOrder(cusOrder)
	if err != nil {
		global.GVA_LOG.Error("更新失败!", zap.Error(err))
		response.FailWithMessage("更新失败:"+err.Error(), c)
		return
	}
	response.OkWithMessage("更新成功", c)
}

// FindCusOrder 用id查询cusOrder表
// @Tags CusOrder
// @Summary 用id查询cusOrder表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query customer.CusOrder true "用id查询cusOrder表"
// @Success 200 {object} response.Response{data=customer.CusOrder,msg=string} "查询成功"
// @Router /cusOrder/findCusOrder [get]
func (cusOrderApi *CusOrderApi) FindCusOrder(c *gin.Context) {
	ID := c.Query("id")
	if ID == "" {
		response.FailWithMessage("参数ID不能为空", c)
		return
	}
	recusOrder, err := cusOrderService.GetCusOrderByID(ID)
	if err != nil {
		global.GVA_LOG.Error("查询失败!", zap.Error(err))
		response.FailWithMessage("查询失败:"+err.Error(), c)
		return
	}
	response.OkWithData(recusOrder, c)
}

// GetCusOrderList 分页获取cusOrder表列表
// @Tags CusOrder
// @Summary 分页获取cusOrder表列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query customerReq.CusOrderSearch true "分页获取cusOrder表列表"
// @Success 200 {object} response.Response{data=response.PageResult,msg=string} "获取成功"
// @Router /cusOrder/getCusOrderList [get]
func (cusOrderApi *CusOrderApi) GetCusOrderList(c *gin.Context) {
	var pageInfo customerReq.CusOrderSearch
	err := c.ShouldBindQuery(&pageInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	list, total, err := cusOrderService.GetCusOrderInfoList(pageInfo)
	if err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败:"+err.Error(), c)
		return
	}
	response.OkWithDetailed(response.PageResult{
		List:     list,
		Total:    total,
		Page:     pageInfo.Page,
		PageSize: pageInfo.PageSize,
	}, "获取成功", c)
}

// GetCusOrderPublic 不需要鉴权的cusOrder表接口
// @Tags CusOrder
// @Summary 不需要鉴权的cusOrder表接口
// @accept application/json
// @Produce application/json
// @Param data query customerReq.CusOrderSearch true "分页获取cusOrder表列表"
// @Success 200 {object} response.Response{data=object,msg=string} "获取成功"
// @Router /cusOrder/getCusOrderPublic [get]
func (cusOrderApi *CusOrderApi) GetCusOrderPublic(c *gin.Context) {
	// 此接口不需要鉴权
	// 示例为返回了一个固定的消息接口，一般本接口用于C端服务，需要自己实现业务逻辑
	response.OkWithDetailed(gin.H{
		"info": "不需要鉴权的cusOrder表接口信息",
	}, "获取成功", c)
}

// GetAllCusOrders 获取所有订单记录
// @Tags CusOrder
// @Summary 获取所有订单记录
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Success 200 {object} response.Response{data=[]customer.CusOrder,msg=string} "获取成功"
// @Router /cusOrder/getAllCusOrders [get]
func (cusOrderApi *CusOrderApi) GetAllCusOrders(c *gin.Context) {
	list, err := cusOrderService.GetAllCusOrders()
	if err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败:"+err.Error(), c)
		return
	}
	response.OkWithDetailed(list, "获取成功", c)
}

// GetCusOrdersByUserID 根据用户ID获取订单列表
// @Tags CusOrder
// @Summary 根据用户ID获取订单列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param userID query string true "用户ID"
// @Success 200 {object} response.Response{data=[]customer.CusOrder,msg=string} "获取成功"
// @Router /cusOrder/getCusOrdersByUserID [get]
func (cusOrderApi *CusOrderApi) GetCusOrdersByUserID(c *gin.Context) {
	//userID := c.Query("userID")
	userID := int(utils.GetUserID(c))
	//if userID == "" {
	//	response.FailWithMessage("用户ID不能为空", c)
	//	return
	//}

	orders, err := cusOrderService.GetOrdersByUserID(userID)
	if err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败:"+err.Error(), c)
		return
	}
	response.OkWithDetailed(orders, "获取成功", c)
}

// FilterCusOrders 根据传入的查询条件筛选 CusOrder 表
// @Tags CusOrder
// @Summary 根据条件筛选 CusOrder 表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query customerReq.SearchParams true "根据条件筛选 CusOrder 表"
// @Success 200 {object} response.Response{data=response.PageResult,msg=string} "筛选成功"
// @Router /cusOrder/filterCusOrders [get]
func (cusOrderApi *CusOrderApi) FilterCusOrders(c *gin.Context) {
	var searchParams customerReq.SearchParams
	if err := c.ShouldBindJSON(&searchParams); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	list, total, err := cusOrderService.FilterCusOrderList(searchParams)
	if err != nil {
		global.GVA_LOG.Error("筛选失败!", zap.Error(err))
		response.FailWithMessage("筛选失败:"+err.Error(), c)
		return
	}

	response.OkWithDetailed(response.PageResult{
		List:     list,
		Total:    total,
		Page:     searchParams.Page,
		PageSize: searchParams.PageSize,
	}, "筛选成功", c)
}
